function ajax(url) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest()
    xhr.open('GET', url)
    xhr.responseType = 'json'
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response)
      } else {
        reject(new Error(this.statusText))
      }
    }
    xhr.send()
  })
}

function * main() {
  const res = yield ajax('/api/user.json')
  console.log(res)

  const res1 = yield ajax('/api/user1.json')
  console.log(res1)

  try {
    const res2 = yield ajax('/api/user1111.json')
    console.log(res2)
  } catch(e) {
    console.log(e)
    console.log('continue')
  }
}

function co(generator) {
  const g = generator();

  function handleResult(result) {
    if (result.done) return;
    result.value.then((val) => {
      handleResult(g.next(val));  // 传出来再传进去，真麻烦
    }, (error) => {
      g.throw(new Error(error));
    })
  }
  handleResult(g.next());
}

async function asyncMain() {
  const res = await ajax('/api/user.json')
  console.log(res)

  const res1 = await ajax('/api/user1.json')
  console.log(res1)

  try {
    const res2 = await ajax('/api/user1111.json')
    console.log(res2)
  } catch(e) {
    console.log(e)
    console.log('continue')
  }
}

async function init() {
  await asyncMain();
  co(main);
}

init();
